package submarine;

import javax.swing.ImageIcon;
import java.awt.Graphics;
import java.io.Serializable;
import java.util.Random;

/**
 * 海洋对象
 */
public abstract class SeaObject implements Serializable {
    public static final int LIVE = 0;
    public static final int DEAD = 1;

    protected int state = LIVE;

    protected int width;
    protected int height;
    protected int x;
    protected int y;
    protected int speed;

    public SeaObject(int width, int height, int x, int y, int speed){
        this.width = width;
        this.height = height;
        this.x = x;
        this.y = y;
        this.speed = speed;
    }
    public SeaObject(int width, int height){
        this.width = width;
        this.height = height;
        x = -width;
        Random ra = new Random();
        y = ra.nextInt(World.HEIGHT-height-150+1)+150;
        speed = ra.nextInt(3)+1;
    }

    public abstract void move();

    public abstract ImageIcon getImage();

    public boolean isLive(){
        return state == LIVE;
    }
    public boolean isDead(){
        return state == DEAD;
    }

    /**
     * 画对象
     * graphics:画笔
     */
    public void paintImage(Graphics g){
        if(this.isLive()){
            this.getImage().paintIcon(null, g, this.x, this.y);
        }
    }

    public boolean isOutOfBounds(){
        return x >= World.WIDTH;
    }

    /**
     * 检测碰撞
     * this : 一个对象
     * other : 另一个对象
     */
    public boolean isHit(SeaObject other){
        int x1 = this.x - other.width;  // x1: 潜艇的x-炸弹的宽
        int x2 = this.x + this.width;   // x2: 潜艇的x+潜艇的宽
        int y1 = this.y - other.height; // y1: 潜艇的y-炸弹的高
        int y2 = this.y + this.height;  // y2: 潜艇的y+潜艇的高
        int x = other.x;    // x: 炸弹的x
        int y = other.y;    // y: 炸弹的y

        return (x>=x1 && x<=x2) && (y>=y1 && y<=y2);
    }

    /**
     * 海洋对象去死
     */
    public void goDead(){
        state = DEAD;
    }

}
